package com.randi.framework.security.handle;

import com.alibaba.fastjson2.JSON;
import com.randi.common.config.AppConfig;
import com.randi.common.core.domain.Result;
import com.randi.common.enums.ResultCode;
import com.randi.common.utils.ServletUtils;
import com.randi.common.utils.StringUtils;
import com.randi.framework.domain.service.impl.SysTokenServiceImpl;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * 认证失败处理
 *
 * @author randi
 */
@Component
public class AuthenticationEntryPointHandle implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -8970718410437077606L;

    @Resource
    private SysTokenServiceImpl tokenService;

    @Resource
    private AppConfig.SystemConfig appSystemConfig;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        authException.printStackTrace();

        String string = JSON.toJSONString(Result.error(ResultCode.AUTH_FAILED));
        boolean isLogoutRequest = request.getRequestURI().contains(appSystemConfig.getLogoutUrl());

        String token = tokenService.getToken(request);
        if (!isLogoutRequest && StringUtils.isNotEmpty(token)) {
            string = JSON.toJSONString(Result.error(ResultCode.TOKEN_EXPIRED));
        }

        String refreshToken = tokenService.getRefreshToken(request);
        if (!isLogoutRequest && StringUtils.isNotEmpty(refreshToken)) {
            string = JSON.toJSONString(Result.error(ResultCode.LOGIN_EXPIRED));
        }

        ServletUtils.renderString(response, string);
    }

}
